import 'dart:io';

import 'package:permission_handler/permission_handler.dart';
import 'package:share_fit/app/controllers/device/call_remind/call_const.dart';
import 'package:share_fit/app/controllers/device/hr/hr_const.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/helper/storage_mixin.dart';
import 'package:share_fit/app/tools/app_const.dart';
import 'package:share_fit/app/tools/locale_tool.dart';
import 'package:share_fit/app/tools/log_utils.dart';
import 'package:share_fit/app/ute/uteped_const.dart';
import 'package:share_fit/app/ute/uteped_helper.dart';
import 'package:share_fit/app/ute/uteped_mixin.dart';
import 'package:share_fit/generated/locales.g.dart';

class UTEPedConfig with UTEPedMixin, StorageMixin implements UTEPedListener {
  /// SDK配置类，用于一些与sdk配置相关的操作

  static const methodSetLogEnable = "setLogEnable";
  static const methodCheckNotificationEnable = "checkNotificationEnable";
  static const methodSyncData = "syncData";
  static const methodSetSyncDataEnable = "setSyncDataEnable";
  static const String methodSetLogFileEnable = "setLogFileEnable";
  static const String methodExitApp = "exitApp"; //退出后台应用
  static const String methodCheckBT3 = "checkBT3"; //BT3一键绑定检测
  static const String methodGetAppInfo = "getAppInfo";// 获取应用信息
  static const String methodSetDeviceFilter = "setDeviceFilter";// 过滤手表型号
  static const String methodUseDatabaseName = "useDatabaseName"; //使用下载数据库
  static const String methodGetNativeValue = "getNativeValue";
  static const String methodGetNativeProp = "getNativeProp";
  static const String methodIsNotificationEnable = "isNotificationEnable";
  static const String methodToNotificationPage = "toNotificationPage";

  // default set
  static const methodSetSmsRemindEnable = "setSmsRemindEnable";
  static const isWeatherSync = "isWeatherSync";
  static const isDefaultValueSet = "isDefaultValueSet";
  static const methodSetTimeDisplay = "setTimeDisplay";

  static final UTEPedConfig instance = UTEPedConfig._();

  UTEPedConfig._();

  void init() {
    initStorage();
    UTEPedHelper.addListener(this);
    getAppInfo().then((value) => {
      save(UTEPedConst.keyAppInfo, value, global: true),
      logger.d(value)
    });
  }

  void setLogEnable(value) {
    /// flutter端开关手表sdk日志
    vRemoteReqAsync(methodSetLogEnable, {UTEPedConst.keyEnable: value});
  }

  void checkNotificationEnable() {
    /// 检查android系统本应用通知是否开启，用于后台进程存活
    vRemoteReqAsync(methodCheckNotificationEnable, {});
  }

  void checkBluetoothPermissions() {
    bRemoteReqAsync(UTEPedConst.methodCheckPermissions, {UTEPedConst.keyPermission: UTEPedConst.permissionBluetooth});
  }

  Future<bool> isNotificationEnable() async {
    return await dRemoteReqAsync(methodIsNotificationEnable, {});
  }

  void toNotificationPage() {
    vRemoteReqAsync(methodToNotificationPage, {});
  }

  void syncData({action = ""}) {
    /// 同步手表数据
    vRemoteReqAsync(methodSyncData, {UTEPedConst.keyAction : action});
  }

  void setSyncDataEnable(value) {
    /// 开关同步数据
    vRemoteReqAsync(methodSetSyncDataEnable, {UTEPedConst.keyEnable: value});
  }

  void setLogFileEnable(value) {
    /// sdk端保存日志文件开关
    vRemoteReqAsync(methodSetLogFileEnable, {UTEPedConst.keyEnable: value});
  }

  void exitApp() {
    /// android退出通知后台服务
    vRemoteReqAsync(methodExitApp, {});
  }

  void checkBT3() {
    /// BT3绑定检测
    vRemoteReqAsync(methodCheckBT3, {});
  }

  void setDeviceFilter(value) {
    /// 开关蓝牙设备过滤
    vRemoteReqAsync(methodSetDeviceFilter, {UTEPedConst.keyEnable: value});
  }

  void useDatabaseName(value) {
    vRemoteReqAsync(methodUseDatabaseName, {UTEPedConst.keyName: value});
  }

  Future<dynamic> getAppInfo() async {
    return dRemoteReqAsync(methodGetAppInfo, {});
  }

  Future<dynamic> getNativeValue(key, type) async {
    return dRemoteReqAsync(methodGetNativeValue, {UTEPedConst.keyName: key, UTEPedConst.keyType: type, UTEPedConst.keyValue: false});
  }

  Future<dynamic> getNativeProp(key) async {
    return dRemoteReqAsync(methodGetNativeProp, {UTEPedConst.keyName: key});
  }

  Future<bool> is24HourFormat() async {
    var is24Hour = await getNativeProp("is24HourFormat");
    return is24Hour;
  }

  @override
  String getRemotePath() {
    return UTEPedConst.pathCommon;
  }

  @override
  String getStoragePath() {
    return UTEPedConst.pathDevice;
  }

  @override
  void onRemoteEvent(event, method) {

  }

  @override
  List<String> getSupportedMethods() {
    return [methodSetSmsRemindEnable, CallConst.methodSetCallRemindEnable];
  }

  @override
  bool useMethodSupport() {
    return true;
  }

  Future<void> setDefaultConfig() async {
    initStorage();
    var isSet = read(isDefaultValueSet, defaultValue: false);
    if (!isSet) {
      await _setDefaultSmsEnable(true);
      await _setDefaultCallRemindEnable(true);
      await _setTimeDisplay(true);
      await _setCloseAllAppRemind(false);
      await _setContinuousBloodOxygenEnable(false);
      await _setHeartRateEnable(true);
      await _setDefaultLanguage();
      await _setUnitDefault();
      if (Platform.isAndroid) {
        await _setSmsReplyDefault();
      }
      save(isDefaultValueSet, true);
    }
  }

  Future<void> _setDefaultSmsEnable (bool value) async {
    if (Platform.isAndroid) {
      bool granted = await Permission.sms.isGranted;
      if (!granted) {
        logger.d("sms permission not granted");
        return;
      }
    }

    bool success = await bRemoteReqAsync(methodSetSmsRemindEnable, {
      UTEPedConst.keyEnable: value,
      UTEPedConst.keyPath: UTEPedConst.pathContact
    });

    if (success) {
      save(methodSetSmsRemindEnable, value);
    }
  }

  Future<void> _setDefaultCallRemindEnable(bool value) async {

    if (Platform.isAndroid) {
      bool granted = await Permission.contacts.isGranted;
      if (!granted) {
        logger.d("contacts permission not granted");
        return;
      }

      granted = await Permission.phone.isGranted;
      if (!granted) {
        logger.d("phone permission not granted");
        return;
      }
    }

    bool success = await bRemoteReqAsync(CallConst.methodSetCallRemindEnable, {
      UTEPedConst.keyEnable: value,
      UTEPedConst.keyPath: UTEPedConst.pathContact
    });

    if (success) {
      save(CallConst.methodSetCallRemindEnable, value);
    }
  }

  void _setWeatherSyncEnable(value) {
    save(isWeatherSync, value);
  }

  Future<void> _setTimeDisplay(value) async {
    bool success = await bRemoteReqAsync(methodSetTimeDisplay, {UTEPedConst.keyTimeFormat: value ? 2 : 1});
    if(success) {
      save(UTEPedConst.keyTimeFormat, value);
    }
  }

  Future<void> _setCloseAllAppRemind(value) async {
    await vRemoteReqAsync(UTEPedConst.methodSetNotificationEnable, {
      UTEPedConst.keyEnable: value,
      UTEPedConst.keyPackage: UTEPedConst.appCloseAll
    });
  }

  Future<void> _setContinuousBloodOxygenEnable(value) async {
    bool success = await bRemoteReqAsync(UTEPedConst.methodSetContinuousBloodOxygen, {
      UTEPedConst.keyEnable: value,
      UTEPedConst.keyPath: UTEPedConst.pathDeviceOptions
    });
    if (success) {
      save(UTEPedConst.methodSetContinuousBloodOxygen, value);
    }
  }

  Future<void> _setDefaultLanguage() async {
    var followSystem = read(UTEPedConst.keyLanguageFollowSystem, defaultValue: false, global: true);
    var language = LocaleTool.getSysLanguage();
    if (!followSystem) {
      language = read(UTEPedConst.keyLanguage, defaultValue: 0, global: true);
    }
    await bRemoteReqAsync(UTEPedConst.methodSetLanguage, {UTEPedConst.keyLanguage: language});
  }

  Future<void> _setHeartRateEnable(value) async {
    bool success = await bRemoteReqAsync(HrConst.setAutoHeartRate, {
      UTEPedConst.keyEnable: value,
      UTEPedConst.keyPath: UTEPedConst.pathDeviceOptions
    });

    if (success) {
      save(HrConst.isHeartRate, value);
    }

  }

  Future<void> _setSmsReplyDefault() async {
    bool success = await bRemoteReqAsync(UTEPedConst.methodSetSmsReplyEnable, {
      UTEPedConst.keyEnable: true,
      UTEPedConst.keyPath: UTEPedConst.pathContact
    });

    if (success) {
      save(UTEPedConst.methodSetSmsReplyEnable, true);
      _syncSmsReplyContent();
    }
  }

  Future<void> _syncSmsReplyContent() async {
    List syncReplyList = [];
    List fixedReplyList = [];
    List replyList = [];

    fixedReplyList.add(LocaleKeys.quick_reply_message_1.ts);
    fixedReplyList.add(LocaleKeys.quick_reply_message_2.ts);
    fixedReplyList.add(LocaleKeys.quick_reply_message_3.ts);
    fixedReplyList.add(LocaleKeys.quick_reply_message_4.ts);
    fixedReplyList.add(LocaleKeys.quick_reply_message_5.ts);

    replyList = read(UTEPedConst.methodSyncSmsReplyContent, defaultValue: []);

    syncReplyList.addAll(fixedReplyList);

    if (replyList.isNotEmpty) {
      syncReplyList.addAll(replyList);
      return;
    }

    await dRemoteReqAsync(UTEPedConst.methodSyncSmsReplyContent, {
      UTEPedConst.typeList: syncReplyList,
      UTEPedConst.keyPath: UTEPedConst.pathContact
    });
  }

  Future<void> _setUnitDefault() async {
    int language = 1;
    if(LocaleTool.locale=='en_US') {
      language = 2;
    }
    String value = await sRemoteReqAsync(UTEPedConst.methodSetLanguage, {UTEPedConst.keyLanguage: language, "units": AppConst.unitsUS, UTEPedConst.keyPath: UTEPedConst.pathSpace});
    if (value == UTEPedConst.codeSuccess.toString()) {
      save(AppConst.spaceUnitLength, AppConst.unitsUS, global: true);
    }

    value = await sRemoteReqAsync(UTEPedConst.methodSetWeightUnits, {UTEPedConst.keyValue: AppConst.unitsUS, UTEPedConst.keyPath: UTEPedConst.pathSpace});
    if (value == UTEPedConst.codeSuccess.toString()) {
      save(AppConst.spaceUnitWeight, AppConst.unitsUS, global: true);
    }

    value = await sRemoteReqAsync(UTEPedConst.methodSetTemperatureUnit, {UTEPedConst.keyValue: AppConst.unitsUS, UTEPedConst.keyPath: UTEPedConst.pathSpace});
    if (value == UTEPedConst.codeSuccess.toString()) {
      save(AppConst.spaceUnitTemperature, AppConst.unitsUS, global: true);
    }
  }
}